package _go

import (
	"gitee.com/tietang/terrace-go/v2/lib/tollgate/handler"
	"github.com/google/gops/goprocess"
	"github.com/shirou/gopsutil/v3/process"
	"strings"
)

type GoProcess struct {
	handler.ServiceProcess
	Port         int
	Args         []string
	Exec         string
	Path         string
	BuildVersion string
	Agent        bool
}

type GoProcessHandler struct {
	handler.BaseProcessHandler
}

func (j *GoProcessHandler) GetProcesses() ([]*handler.ServiceProcess, error) {
	gopss := goprocess.FindAll()
	processes := make([]*handler.ServiceProcess, 0)
	for _, p := range gopss {
		gp := &GoProcess{}
		gp.Pid = p.PID
		gp.PPid = p.PPID
		gp.Path = p.Path
		gp.Exec = p.Exec
		gp.BuildVersion = p.BuildVersion
		gp.Agent = p.Agent

		gp.ServiceId = j.Replace(p.Exec)

		if gp.ServiceId != "" {
			pss, err := process.NewProcess(int32(gp.Pid))
			if err != nil {
				continue
			}
			gp.Process = pss
			j.parseArgs(gp)
			gp.ListenedAddrs = j.GetAddrs(pss)
			processes = append(processes, gp.Clone())
		}
	}
	return processes, nil
}

func (j *GoProcessHandler) parseArgs(p *GoProcess) {

	args, err := p.Process.CmdlineSlice()
	if err != nil {
		return
	}
	for _, arg := range args {
		if strings.Index(arg, "-D") >= 0 {
			kvs := strings.Split(arg, "=")
			key := kvs[0][2:]
			value := kvs[1]
			k := string(key)
			p.Labels[k] = handler.KV{Key: k, Value: string(value)}
			p.ParseServiceId()
			p.ParseHealthCheckUrl()
			p.ParsePort()
		} else {
			p.Args = append(p.Args, arg)
		}
	}
}
